package net.esj.basic.service.provider;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import net.esj.basic.pojo.system.UserRule;

public abstract class UserRuleProvider {

	private static Map<Class, UserRule> userRuleCache = new HashMap<Class, UserRule>();
	
	public static final UserRule getUserRule(Class clazz){
		return userRuleCache.get(clazz);
	}
	
	public static final Collection<UserRule> allUserRules(){
		return userRuleCache.values();
	}
	
	public static final synchronized void resetUserRules(List<UserRule> rules){
		userRuleCache.clear();
		for(UserRule rule : rules){
			userRuleCache.put(rule.getUserClass(), rule);
		}
	}
	
	public static final <T> T getSessionUser(HttpSession session,Class<T> clazz){
		UserRule rule = getUserRule(clazz);
		if(rule!=null){
			return (T) session.getAttribute(rule.getSessionKey());
		}
		return null;
	}
	
	public static final Map getSessionBag(HttpSession session,Class clazz){
		UserRule rule = getUserRule(clazz);
		if(rule!=null){
			return  (Map) session.getAttribute(rule.getSessionBag());
		}
		return null;
	}
	
	public static final <T> T getSessionUser(HttpSession session,String authModel){
		for(UserRule rule : userRuleCache.values()){
			if(StringUtils.equals(rule.getAuthModel(), authModel)){
				return  (T) session.getAttribute(rule.getSessionKey());
			}
		}
		return null;
	}
	
	public static class TestUserRule implements UserRule{
		private Class userClass;
		private String sessionKey;
		private String sessionBag;
		private String authModel;
		public Class getUserClass() {
			return userClass;
		}
		public void setUserClass(Class userClass) {
			this.userClass = userClass;
		}
		public String getSessionKey() {
			return sessionKey;
		}
		public void setSessionKey(String sessionKey) {
			this.sessionKey = sessionKey;
		}
		public String getSessionBag() {
			return sessionBag;
		}
		public void setSessionBag(String sessionBag) {
			this.sessionBag = sessionBag;
		}
		public String getAuthModel() {
			return authModel;
		}
		public void setAuthModel(String authModel) {
			this.authModel = authModel;
		}
		
	}
}
